<!--发布说说-->
<style>
.contain {
  height: 100%;
  margin-left: 5px;
  margin-right: 5px;
}

</style>
<template>
  <div class="contain">
    <form class="form-inline" id="thought-form" enctype="multipart/form-data" accept-charset="UTF-8">
      <input type="hidden" name="userId" v-model="userId">
      <input type="hidden" name="base64Datas" id="base64Datas" v-model="base64Datas">
      <group>
        <x-textarea :max="20" :placeholder="('说...')" name="thought" v-model="thought"></x-textarea>
      </group>
      <div class="weui-cells weui-cells_form" id="uploader">
        <div class="weui-cell">
          <div class="weui-cell__bd">
            <div class="weui-uploader">
              <div class="weui-uploader__hd">
                <p class="weui-uploader__title">图片上传</p>
                <div class="weui-uploader__info"><span id="uploadCount">0</span>/5</div>
              </div>
              <div class="weui-uploader__bd">
                <ul class="weui-uploader__files" id="uploaderFiles" @click="handleClickUploadList"></ul>
                <div class="weui-uploader__input-box">
                  <input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" capture="camera" multiple="" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>
    <x-button type="primary" action-type="button" @click.native="publish()">发 布</x-button>
  </div>
</template>
<script>
import { XButton, XTextarea, Group, XInput } from 'vux'
import weui from '../../static/js/weui.min.js'

var uploadCount = 0 //初始化 上传的图片数量
var uploadCountDom = null //初始化 显示上传图片数量的dom元素
var uploadList = [] //初始化 选择的图片列表
var successImgList = [] //初始化 成功上传的图片列表
var uploadListH = []

export default {
  components: {
    XButton,
    XTextarea,
    Group,
    XInput
  },
  data() {
    return {
      userId: window.localStorage["userId"],
      base64Datas: '',
      thought: ''
    }
  },
  mounted() {
    uploadCountDom = document.getElementById("uploadCount")
    weui.uploader("#uploader", {
      url: '',
      auto: false,
      type: 'file',
      fileVal: 'file',
      // compress: {
      // 	width: 512,
      // 	height: 512
      // },
      onBeforeQueued: function(files) {
        if (['image/jpg', 'image/jpeg', 'image/png', 'image/gif'].indexOf(this.type) < 0) {
          weui.alert("请上传图片")
          return false
        }
        if (this.size > 1048576) {
          weui.alert("请上传不超过1M的图片")
          return false
        }
        if (this.length > 5) {
          weui.alert("最多只能上传5张图片，请重新选择")
          return false
        }
        if (uploadCount > 4) {
          weui.alert("最多只能上传5张图片")
          return false
        }
        ++uploadCount
        uploadCountDom.innerHTML = uploadCount
      },
      onQueued: function() {
        uploadList.push(this)
        var reader = new window.FileReader();
        reader.readAsDataURL(this);
        reader.onloadend = function() {
          let base64data = reader.result;
          uploadListH.push(base64data)
        }
      },
      onBeforeSend: function(data, headers) {

      },
      onProgress: function(procent) {

      },
      onSuccess: function(ret) {
        console.log('--onSuccess--', this, ret)
        successImgList.push({
          id: this.id,
          key: ret.key
        })
      },
      onError: function(err) {}
    })
  },
  methods: {
    handleClickUploadList(e) {
      var target = e.target
      while (!target.classList.contains('weui-uploader__file') && target) {
        target = target.parentNode
      }
      if (!target) return
      var url = target.getAttribute('style') || ''
      var id = target.getAttribute('data-id')
      if (url) {
        url = url.match(/url\((.*?)\)/)[1].replace(/"/g, '')
      }
      var gallery = weui.gallery(url, {
        className: 'custom-name',
        onDelete: function() {
          //						weui.confirm('确定删除该图片?', function() {
          uploadCount--
          uploadCountDom.innerHTML = uploadCount
          for (let i = 0, len = uploadList.length; i < len; i++) {
            var file = uploadList[i]
            if (file.id + '' === id) {
              uploadList.splice(i, 1) //删除当前元素
              uploadListH.splice(i, 1) //删除当前元素
              break
            }
          }
          for (let i = 0, len = successImgList.length; i < len; i++) {
            var item = successImgList[i]
            if (item.id + '' === id) {
              successImgList.splice(i, 1)
              break
            }
          }
          target.remove()
          gallery.hide()
          //						})
        }
      })
    },
    publish() {
      let _that = this
      $("#base64Datas").val(uploadListH.join("##"))
      $("#thought-form").ajaxSubmit({
        type: 'POST',
        url: this.$domain + "/tld/admin/pthought/publish.json",
        success: function(json) {
          _that.$store.commit('updateToast', '发布成功');
          setTimeout(() => {
            _that.$router.push({
              path: '/'
            })
          }, 1500)
        }
      });
    }
  }
}

</script>
